package com.ad.pet.common.data.http.interceptor;

import android.text.TextUtils;

import com.ad.pet.Logger;

import java.io.IOException;
import java.net.URLDecoder;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * Created by ems on 2017/2/27.
 * okHttp 拦截类，用于打印请求信息 以及响应信息
 */

public class LoggerInterceptor implements Interceptor {
    public static final String TAG = "LoggerInterceptor";
    private String tag;
    private boolean showResponse;

    public LoggerInterceptor(String tag, boolean showResponse) {
        if (TextUtils.isEmpty(tag)) {
            tag = TAG;
        }
        this.showResponse = showResponse;
        this.tag = tag;
    }

    public LoggerInterceptor(String tag) {
        this(tag, false);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        LoggerForRequest(request);
        Response response = chain.proceed(request);
        if (response == null) {
            Logger.e("response==null");
        }
        return LoggerForResponse(response);
    }

    private Response LoggerForResponse(Response response) {
        try {
            StringBuilder sb = new StringBuilder();
            //===>response Logger
            sb.append("========response'Logger=======\n");
            Response.Builder builder = response.newBuilder();
            Response clone = builder.build();
            sb.append("url : " + clone.request().url() + "\n");
            sb.append("code : " + clone.code() + "\n");
            sb.append("protocol : " + clone.protocol() + "\n");
            if (!TextUtils.isEmpty(clone.message()))
                sb.append("message : " + clone.message() + "\n");

            if (showResponse) {
                ResponseBody body = clone.body();
                if (body != null) {
                    MediaType mediaType = body.contentType();
                    if (mediaType != null) {
                        sb.append("responseBody's contentType : " + mediaType.toString() + "\n");
                        if (isText(mediaType)) {
                            String resp = body.string();
                            sb.append("responseBody's content :\n " + resp + "\n");
//                            Logger.d("responseBody's content : " + resp);

                            body = ResponseBody.create(mediaType, resp);

                            Logger.d(TAG, sb.toString());

                            return response.newBuilder().body(body).build();
                        } else {
                            sb.append("responseBody's content : " + " maybe [file part] , too large too print , ignored!\n");
                        }
                    }
                }
            }

            sb.append("========response'Logger=======end\n");
//            Logger.d(TAG, new String(sb.toString().getBytes(),"UTf-8"));
            Logger.d(TAG, sb.toString());
        } catch (Exception e) {
//            e.printStackTrace();
        }

        return response;
    }

    private void LoggerForRequest(Request request) {

        try {
            StringBuilder sb = new StringBuilder();
            String url = request.url().toString();

            Headers headers = request.headers();
            sb.append("========request'Logger=======\n");
//            Logger.d("========request'Logger=======");
            sb.append("method : " + request.method() + "\n");
            sb.append("url : " + url + "\n");
//            Logger.d("method : " + request.method());
//            Logger.d("url : " + url);
            if (headers != null && headers.size() > 0) {
                sb.append("headers : " + headers.toString() + "\n");
//                Logger.d("headers : " + headers.toString());
            }
            RequestBody requestBody = request.body();
            if (requestBody != null) {
                MediaType mediaType = requestBody.contentType();
                if (mediaType != null) {
                    sb.append("requestBody's contentType : " + mediaType.toString() + "\n");
                    if (isText(mediaType)) {
                        sb.append("requestBody's content :\n " + bodyRequestToString(request) + "\n");
                    } else {
                        sb.append("requestBody's content : " + " maybe [file part] , too large too print , ignored!\n");
                    }
                }
            }
            sb.append("========request'Logger=======end\n");
            Logger.d(TAG, sb.toString());
        } catch (Exception e) {
//            e.printStackTrace();
            Logger.e(TAG, "解析过滤器出现异常 ", e);
        }
    }

    private boolean isText(MediaType mediaType) {
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype().equals("json") ||
                    mediaType.subtype().equals("xml") ||
                    mediaType.subtype().equals("html") ||
                    mediaType.subtype().equals("webviewhtml") ||
                    mediaType.subtype().equals("x-www-form-urlencoded")
                    )
                return true;
        }
        return false;
    }

    private String bodyToString(final Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "something error when show requestBody.";
        }
    }

    private String bodyRequestToString(final Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return URLDecoder.decode(buffer.readUtf8(), "UTF-8");
        } catch (final IOException e) {
            return "something error when show requestBody.";
        }
    }
}
